package com.data.structure;

public class TwoWayLinkedList {

    private Node head ;//链表头
    private Node tail;//链表尾
    private int length;//链表长度
    private class Node{
        private Object data;
        private Node next;
        private Node prev;
        public Node(Object data){
            this.data = data;
        }

    }

    public TwoWayLinkedList(){
        length = 0;
        head = null;
        tail = null;
    }

    //链表头部增加节点
    public void addHead(Object value){
        Node newNode = new Node(value);
        if(length==0){
            head = newNode;
            tail = newNode;
            length++;
        }else{
            newNode.next=head;
            head.prev = newNode;
            head = newNode;
            length++;
        }
    }
    //链表尾部增加节点
    public void addTail(Object value){
        Node newNode = new Node(value);
        if(length==0){
            head = newNode;
            tail = newNode;
            length++;
        }else{
            newNode.prev=tail;
            tail.next=newNode;
            tail=newNode;
            length++;
        }
    }
    public Node deleteHead(){
        Node temp = head;
        if(length!=0){
            head = head.next;
            head.prev = null;
            length--;
            return temp;
        }else{
            return null;
        }
    }

    //删除链表尾部节点
    public Node deleteTail(){
        Node temp = tail;
        if(length != 0){
            tail = tail.prev;
            tail.next = null;
            length--;
            return temp;
        }else{
            return null;
        }
    }

    public  void  iterator(){
        //System.out.println("遍历链表");
        TwoWayLinkedList.Node current = head;
        int tempSize = length;
        while(tempSize>0){
            System.out.print(current.data+"->");
            current = current.next;
            tempSize--;
        }
        System.out.println();
    }

    public static void main(String[] args){
        TwoWayLinkedList twld = new TwoWayLinkedList();
        for(int i=0;i<10;i++){
            twld.addHead(i);
        }
        System.out.println("头部添加10个元素");
        twld.iterator();
        for(int i=100;i<110;i++){
            twld.addTail(i);
        }
        System.out.println("尾部添加10个元素");
        twld.iterator();
        twld.deleteHead();
        System.out.println("头部删除一个元素");
        twld.iterator();
        twld.deleteTail();
        System.out.println("尾部删除一个元素");
        twld.iterator();

    }

    @Override
    public String toString() {
        return "TwoWayLinkedList{" +
                "head=" + head +
                ", tail=" + tail +
                ", length=" + length +
                '}';
    }
}
